package mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;

import java.util.ArrayList;

import org.bson.Document;
import org.bson.types.ObjectId;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class TeachingMaterialsType {
	
    MongoDatabase mongoDatabase = null;
    MongoCollection<Document> TeachingMaterialsType;
    
    public TeachingMaterialsType(){
        try{
        	mongoDatabase = mongoConnet.getMongoDatabase();
        	TeachingMaterialsType = mongoDatabase.getCollection("TeachingMaterialsType");
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
    
    public  MongoCursor<Document> list(){
        try{
            FindIterable<Document> findIterable = TeachingMaterialsType.find();
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            return mongoCursor;
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return null;
        }
    }
    
    
    public Boolean add(Document type){
    	try{
    		TeachingMaterialsType.insertOne(type);
    		return true;
    	}catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return false;
    	}
    }
    
    
    public boolean update(ObjectId id,Document document){
        try{
        	TeachingMaterialsType.updateOne(Filters.eq("_id", id), new Document("$set",document));
            return true;
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return false;
        }
    }
    
    public boolean delete(ObjectId id){
        try{
            BasicDBObject queryObject = new BasicDBObject("_id",id);
            TeachingMaterialsType.deleteOne(queryObject);
            return true;
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return false;
        }
    }
    
    public Boolean isExist(String typeid){
        try{
            BasicDBObject queryObject = new BasicDBObject("id",typeid);
            FindIterable<Document> findIterable = TeachingMaterialsType.find(queryObject);
            MongoCursor<Document> mongoCursor = findIterable.iterator();
            if(mongoCursor.hasNext()){
            	return true;
            }else{
            	return false;
            } 
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
            return false;
        }
    }
}
